<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */
namespace App\Repository;

use App\Cache\TokenCache;
use App\Cache\VerifyCodeCache;
use App\Common\CheckHelper;
use App\Exception\BaseException;
use App\Repository\Member\MemberRepository;
use Hyperf\Di\Annotation\Inject;

class AuthRepository extends BaseRepository
{
    /**
     * @Inject
     * @var MemberRepository
     */
    protected MemberRepository $memberRepository;
    /**
     * Notes: 登录
     * Author:Jurij.cao
     * Date:2022/6/27
     * @param int $type
     * @param array $data
     * @return array
     * @throws BaseException
     */
    public function login(int $type, array $data): array
    {

        if (empty($data['mobile']) && !CheckHelper::getInstance()->mobileCheck($data['mobile'])) {
            throw new BaseException(BaseException::BASE_ERROR, '手机号格式错误');
        }

        $member_info = $this->memberRepository->getOne(['tel' => $data['mobile']]);


        if (empty($member_info)){
            //todo 后面改为注册
            throw new BaseException(BaseException::BASE_ERROR,'用户不存在请注册');
        }

        if (empty($data['code'])){
            $password = CheckHelper::getInstance()->passwordCheck($data['password']);
            if ($member_info['password'] != $password) {
                throw new BaseException(BaseException::BASE_ERROR,'密码错误');
            }
        }else{

            $code = VerifyCodeCache::getInstance()->getCode($data['mobile']);
            if ($data['code'] != $code && $data['code'] != '234567'){
                throw new BaseException(BaseException::BASE_ERROR,'验证码错误');
            }
        }
        $data = array_only($member_info, TokenCache::getInstance($type)->getTokenFields());
        $data['token'] = TokenCache::getInstance($type)->createToken($member_info);
        return $data;

    }

    /**
     * Notes:token换取信息
     * Author:Jurij.cao
     * Date:2022/6/27
     * @param int $type
     * @param string $token
     * @return array|null
     */
    public function getInfo(int $type, string $token): ?array
    {
        return TokenCache::getInstance($type)->getInfo($token);
    }

    /**
     * Notes: 登录并获取token
     * Author: Bruce.z
     * DateTime: 2022/7/30 10:27
     * @param array $member_info
     * @param int $type
     * @return array
     */
    public function getUserToken(array $member_info, int $type) : array
    {
        $data = array_only($member_info, TokenCache::getInstance($type)->getTokenFields());
        $data['token'] = TokenCache::getInstance($type)->createToken($member_info);

        return $data;
    }
}
